import axios from 'axios'
import createAPI from './interface'
import iView from 'iview'

/**
 * BASE_URL
 * 开发、部署环境配置
 */
// const BASE_URL = process.env.NODE_ENV === 'development' ? 'http://116.62.167.113:8000' : location.pathname
const BASE_URL = 'http://116.62.167.113:8000'

/**
 * 通用请求 application/json
 * application/json
 * @param {String} url
 * @param {Object} params
 */
async function postJson(url, params = {}, showLoading = true) {
  let result = {}
  if (showLoading) {
    iView.LoadingBar.start();
  }
  let headers = {
    'Content-Type': 'application/json',
    token: sessionStorage.token || ''
  }
  let instance = axios.create({headers,
    timeout: 20000
  })
  try {
    result = await instance.post(BASE_URL + url, params)
  } catch (e) {
    result = { data: null }
  }finally{
    iView.LoadingBar.finish();
  }
  return result.data
}

async function getJson(url, showLoading = true) {
  let result = {}
  if (showLoading) {
    iView.LoadingBar.start();
  }
  let headers = {
    'Content-Type': 'application/json',
  }
  let instance = axios.create({headers,
    timeout: 20000
  })
  try {
    result = await instance.get(BASE_URL + url)
  } catch (e) {
    result = { data: null }
  }finally{
    iView.LoadingBar.finish();
  }
  return result.data
}
/**
 * 通用上传文件
 * @param {*} url 
 * @param {*} params 
 * @param {*} base 
 */
async function postFile(url, params, base = '') {
  let result = {}
  iView.LoadingBar.start();
  let instance = axios.create({
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    timeout: 20000
  })
  let u = base || BASE_URL
  try {
    result = await instance.post(u + url, params)
  } catch (e) {
    result = { data: null }
  } finally {
    iView.LoadingBar.finish();
  }
  return result.data
}
/**
 * export
 */
export default {
  install: (v) => {
    v.prototype.$postJson = postJson
    v.prototype.$getJson = getJson
    v.prototype.$postFile = postFile
    v.prototype.$API = createAPI(BASE_URL)
  }
}
